/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.allscore.batch.test.service;

import com.allscore.batch.test.util.DateUtils;
import java.util.Collection;
import java.util.HashMap;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Administrator
 */
@Service
public class BatchService {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job productJob;

    public HashMap<String, Object> productBatch(long id) {

        HashMap<String, Object> result = new HashMap<String, Object>();

        StepExecution stepResult = null;

        JobExecution jobResult = null;

        JobParameters jobParameters = new JobParametersBuilder().addLong("orderTm", System.currentTimeMillis()) // 必须传参，而且保证每次得有个不一样的参数，不能相同！
                .addLong("id", id).toJobParameters();
        try {
            // 启动任务，并获取整个任务执行结果
            jobResult = jobLauncher.run(productJob, jobParameters);

            // 获取步骤step的结果集
            Collection<StepExecution> steps = jobResult.getStepExecutions();

            // 获取第一个step
            stepResult = steps.iterator().next();

            result.put("ReadCount", stepResult.getReadCount());// 总计输入数量

            result.put("WriteCount", stepResult.getWriteCount());// 总计输出数量

            result.put("StartTime", DateUtils.convertJavaDateToStr(stepResult.getStartTime(), "yyyy-MM-dd HH:mm:ss"));// 开始执行时间

            result.put("EndTime", DateUtils.convertJavaDateToStr(stepResult.getEndTime(), "yyyy-MM-dd HH:mm:ss"));// 执行结束的时间

            result.put("FilterCount", stepResult.getFilterCount());// 被ItemProcessor过滤的记录数

            result.put("SkipCount", stepResult.getSkipCount());// 总计跳过数量

            result.put("ReadSkipCount", stepResult.getReadSkipCount());// 输入失败跳过的记录数

            result.put("WriteSkipCount", stepResult.getWriteSkipCount());// 输出失败跳过的记录数

            result.put("ProcessSkipCount", stepResult.getProcessSkipCount());// 处理失败而略过的记录数

            result.put("CommitCount", stepResult.getCommitCount());// 事务成功提交次数，非记录数

            result.put("RollbackCount", stepResult.getRollbackCount());// 事务回滚次数，非记录数

            result.put("ExitStatusCode", stepResult.getExitStatus().getExitCode());// 退出(异常退出或执行完成退出)后的状态，UNKNOWN

            result.put("Status", stepResult.getStatus());// STARTING STARTED FAILED STOPPING STOPPED COMPLETED
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

}
